package com.cloudcc.cloudframe.net.async;

import com.cloudcc.cloudframe.net.CanCheckable;
import com.cloudcc.cloudframe.net.ErrorInfo;
import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.google.gson.JsonSyntaxException;
import com.google.gson.reflect.TypeToken;
import com.litesuits.android.log.Log;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;

/**
 * @Description: 泛型自动解析 json数据的请求
 * @author wangzhiqiang
 * @date 2015-11-24 下午2:33:15
 * 
 * @param <T>
 */
public abstract class GenericsRequest<T> extends JsonRequest implements
		CanCheckable {

	@Override
	public void handleSuccess(JsonObject json, String resp) {
		// 获得父类的泛型 这个地方使用的时候注意 this 当前是子类的 所以 如果直接使用 GenericsRequest 一定要 {}
		// 创建一个子类
		Log.d("jsonElement", resp);
		ParameterizedType genericSuperclass = (ParameterizedType) this
				.getClass().getGenericSuperclass();
		Type type = genericSuperclass.getActualTypeArguments()[0];
		TypeToken<?> typeToken = TypeToken.get(type);
		JsonElement jsonElement = json.get(getUsefullNode());

		Log.d("rootJsonObject", " sdfv  " + json.get("memberinfo") + "   "
				+ jsonElement.toString());
		T data = null;
		Log.d("url", (json.get("url") != null)+" "+("".equals(json.get("url"))));
		if (json.get("url") != null | !("".equals(json.get("url")))) {
			try {
				JSONObject jsonObj = new JSONObject(json.get(getUsefullNode())
						.toString());
				jsonObj.put("url", json.get("url"));
				Log.d("qiandao", "有url成功" + jsonObj.toString());
				JsonObject rootJsonObject = null;
				JsonParser jsonParser = new JsonParser();
				rootJsonObject = jsonParser.parse(jsonObj.toString())
						.getAsJsonObject();
				jsonElement = rootJsonObject;
				Log.d("qiandao", jsonElement.toString());
			} catch (JSONException e) {
				Log.d("qiandao", "木有url失败");
			}
		}
		int isname = 0;
		try {
			JSONObject jsonObject = new JSONObject(resp);
			JSONObject jo = null;

			JSONArray jsonArray = jsonObject.getJSONArray("data");

			Log.d("getfield", "解析上一步");
			JsonElement jsonElement2 = json.get("fields");
			Log.d("getfield", "解析下一步");
			JsonArray jsonArrayfield = jsonElement2.getAsJsonArray();
			// name
			StringBuilder sbname = new StringBuilder();
			// value
			StringBuilder sbvalue = new StringBuilder();
			List<String> list = new ArrayList<String>();
			
			for (int i = 0; i < jsonArrayfield.size(); i++) {
				String name = jsonArrayfield.get(i).getAsJsonObject()
						.get("key").toString();
				if("name".equals(name.substring(1, name.length()-1))){
					isname = i+1;
				}
				String value = jsonArrayfield.get(i).getAsJsonObject()
						.get("value").toString();
				// sbname.append(name+",");
				sbvalue.append(value + ",");
				Log.d("getfield",
						jsonArrayfield.get(i).getAsJsonObject().get("key")
								.toString());
				Log.d("getfield",
						jsonArrayfield.get(i).getAsJsonObject().get("value")
								.toString());
				list.add(name);

			}
//			Jxmedel jx = new Jxmedel();
//
//			jx.setIsname(isname);
//			Log.d("jsonArrayfield", "成功获取");
//		
//			EventBus.getDefault().post(jx);
			// Log.d("jiexishuju111", "daozhele"+list.get(1));

			for (int j = 0; j < jsonArray.length(); j++) {
				jo = jsonArray.getJSONObject(j);
				Log.d("jiexishuju111", "daozhele");
				for (int i = 0; i < list.size(); i++) {
//					Log.d("listneirong", list.get(i) + " " + list.size());
//					Log.d("jiexishuju222",
//							"daozhele"
//									+ jo.getString(list.get(i).substring(1,
//											list.get(i).length() - 1)));
					String na = list.get(i).substring(1,
							list.get(i).length() - 1);
//					if("".equals(jo.get(na))){
//						jo.get(na) = null;
//					}
					sbname.append(jo.opt(na) + "*");

				}
				Log.d("jiexishuju333", "daozhele" + sbname);
				String sbna = sbname.toString();
				jo.put("key", sbna);
				Log.d("jode1", "daozhele" + jo.toString());
				jo.put("value", sbvalue);
				jo.put("isname", isname);

				sbname.delete(0, sbname.length());
			}
			Log.d("jode2", "daozhele" + jsonArray.toString());
			JsonObject rootJsonObject = null;
			JsonParser jsonParser = new JsonParser();
			rootJsonObject = jsonParser.parse(jsonObject.toString())
					.getAsJsonObject();
			jsonElement = rootJsonObject.get(getUsefullNode());
			Log.d("rootJsonObject1", jsonElement.toString());
		} catch (Exception e) {
			Log.d("rootJsonObject3", "field失败" + jsonElement.toString());
		}
		Log.d("shifoushijson", jsonElement.toString().substring(0, 1) + "   "
				+ "到底是不是");
		try {
			data = new Gson().fromJson(jsonElement, typeToken.getType());
//			Log.d("zoudaolenali",
//					"解析成功" + typeToken.getType() + data.toString());
		} catch (JsonSyntaxException e) {
			Log.d("zoudaolenali", "解析失敗" + typeToken.getType());
			handleFailure(ErrorInfo.get(JSON_PARSER_ERROR));
			return;
		}
		if (data == null) {
			Log.d("zoudaolenali", "解析數據為空");
			handleFailure(ErrorInfo.get(JSON_PARSER_ERROR));
		} else {
			handleSuccess(data);
		}
	}

	/**
	 * json数据的额存储节点
	 * 
	 * @return 默认是data 可以自定义
	 */
	protected String getUsefullNode() {
		return "data";
	}

	/**
	 * 成功
	 * 
	 * @param data
	 */
	public abstract void handleSuccess(T data);

	@Override
	public void onCheckFinish(boolean isOk, int code, String message) {
		if (!isOk) {
			handleFailure(ErrorInfo.get(code, message));
		}
	}

}
